<script setup lang="ts">
  import { ref, onMounted } from 'vue'

  // 定义用户接口
  interface User {
    id: number
    name: string
    email: string
    age: number
    active: boolean
  }

  // 定义表单数据接口
  interface UserForm {
    name: string
    email: string
    age: number
  }

  // 使用ref定义响应式数据
  const users = ref<User[]>([])
  const selectedUser = ref<User | null>(null)
  const isEditing = ref(false)

  // 表单数据
  const formData = ref<UserForm>({
    name: '',
    email: '',
    age: 0,
  })

  // 定义错误信息
  const errors = ref<Partial<Record<keyof UserForm, string>>>({})

  // 验证表单
  const validateForm = (): boolean => {
    const newErrors: Partial<Record<keyof UserForm, string>> = {}

    if (!formData.value.name.trim()) {
      newErrors.name = '名称不能为空'
    }

    if (!formData.value.email.trim()) {
      newErrors.email = '邮箱不能为空'
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.value.email)) {
      newErrors.email = '邮箱格式不正确'
    }

    if (formData.value.age <= 0) {
      newErrors.age = '年龄必须大于0'
    }

    errors.value = newErrors
    return Object.keys(newErrors).length === 0
  }

  // 添加用户
  const addUser = () => {
    if (!validateForm()) return

    const newUser: User = {
      id: Date.now(), // 使用时间戳作为临时ID
      ...formData.value,
      active: true,
    }

    users.value.push(newUser)
    resetForm()
  }

  // 开始编辑用户
  const startEdit = (user: User) => {
    selectedUser.value = user
    formData.value = {
      name: user.name,
      email: user.email,
      age: user.age,
    }
    isEditing.value = true
  }

  // 更新用户
  const updateUser = () => {
    if (!validateForm() || !selectedUser.value) return

    const index = users.value.findIndex((u) => u.id === selectedUser.value?.id)
    if (index !== -1) {
      users.value[index] = {
        ...users.value[index],
        ...formData.value,
      }
      isEditing.value = false
      resetForm()
    }
  }

  // 删除用户
  const deleteUser = (id: number) => {
    users.value = users.value.filter((user) => user.id !== id)
  }

  // 切换用户状态
  const toggleUserStatus = (user: User) => {
    user.active = !user.active
  }

  // 重置表单
  const resetForm = () => {
    formData.value = {
      name: '',
      email: '',
      age: 0,
    }
    selectedUser.value = null
    isEditing.value = false
    errors.value = {}
  }

  // 模拟加载初始数据
  onMounted(() => {
    // 模拟API调用
    const mockUsers: User[] = [
      { id: 1, name: '张三', email: 'zhangsan@example.com', age: 25, active: true },
      { id: 2, name: '李四', email: 'lisi@example.com', age: 30, active: true },
    ]
    users.value = mockUsers
  })
</script>

<template>
  <div class="user-list">
    <h2>用户管理</h2>

    <!-- 用户表单 -->
    <form @submit.prevent="isEditing ? updateUser() : addUser()" class="user-form">
      <div class="form-group">
        <label for="name">姓名：</label>
        <input id="name" v-model="formData.name" type="text" :class="{ error: errors.name }" />
        <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
      </div>

      <div class="form-group">
        <label for="email">邮箱：</label>
        <input id="email" v-model="formData.email" type="email" :class="{ error: errors.email }" />
        <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
      </div>

      <div class="form-group">
        <label for="age">年龄：</label>
        <input
          id="age"
          v-model.number="formData.age"
          type="number"
          :class="{ error: errors.age }"
        />
        <span v-if="errors.age" class="error-message">{{ errors.age }}</span>
      </div>

      <div class="form-actions">
        <button type="submit">
          {{ isEditing ? '更新' : '添加' }}
        </button>
        <button type="button" @click="resetForm">重置</button>
      </div>
    </form>

    <!-- 用户列表 -->
    <table class="users-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>邮箱</th>
          <th>年龄</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id" :class="{ inactive: !user.active }">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.email }}</td>
          <td>{{ user.age }}</td>
          <td>
            <button @click="toggleUserStatus(user)" :class="{ active: user.active }">
              {{ user.active ? '启用' : '禁用' }}
            </button>
          </td>
          <td>
            <button @click="startEdit(user)">编辑</button>
            <button @click="deleteUser(user.id)" class="delete">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
  .user-list {
    padding: 20px;
  }

  .user-form {
    margin-bottom: 20px;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .form-group {
    margin-bottom: 15px;
  }

  .form-group label {
    display: block;
    margin-bottom: 5px;
  }

  .form-group input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .form-group input.error {
    border-color: #ff4444;
  }

  .error-message {
    color: #ff4444;
    font-size: 0.8em;
    margin-top: 5px;
  }

  .form-actions {
    margin-top: 20px;
  }

  .form-actions button {
    margin-right: 10px;
  }

  .users-table {
    width: 100%;
    border-collapse: collapse;
  }

  .users-table th,
  .users-table td {
    padding: 10px;
    border: 1px solid #ddd;
    text-align: left;
  }

  .users-table th {
    background-color: #f5f5f5;
  }

  .users-table tr.inactive {
    background-color: #f9f9f9;
    color: #999;
  }

  button {
    padding: 5px 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background-color: #4caf50;
    color: white;
    margin-right: 5px;
  }

  button.delete {
    background-color: #ff4444;
  }

  button.active {
    background-color: #2196f3;
  }

  button:hover {
    opacity: 0.8;
  }
</style>
